<template>
  <div class="dialog-container">
    <el-dialog
      :title="dialogType==='add'?'添加排口':dialogType === 'detail'?'排口详情':'修改排口'"
      :visible="dialogVisible"
      @open="initData"
      @close="closeDialog"
    >
      <el-form
        ref="form"
        v-loading="formLoading"
        :model="dataForm"
        class="dialog-form"
        :rules="rules"
        label-width="110px"
        size="mini"
        :disabled="dialogType === 'detail'"
      >
        <template>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="排口基本信息" name="first">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="排放口名称" prop="outletName">
                    <el-input v-model="dataForm.outletName" placeholder="请输入排放口名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="排放口类型" prop="outletType">
                    <el-select v-model="dataForm.outletType" class="w-100" placeholder="请输入排放类型">
                      <el-option
                        v-for="(item,index) in outletTypes"
                        :key="index+'outletType'"
                        :value="item.code"
                        :label="item.codeName"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="排放口mn" prop="outletMn">
                    <el-input v-model="dataForm.outletMn" placeholder="请输入排放口mn" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="排放口规范编号" prop="outletCode">
                    <el-input v-model="dataForm.outletCode" placeholder="请输入排放口规范编号" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所属项目部" prop="projectDepartmentId">
                    <el-select v-model="dataForm.projectDepartmentId" class="w-100" placeholder="请输入所属项目部" @change="selectEnterprise">
                      <el-option
                        v-for="(item,index) in projectDepartmentIds"
                        :key="index+'projectDepartmentId'"
                        :value="item.id"
                        :label="item.name"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所属企业" prop="enterpriseId">
                    <el-select v-model="dataForm.enterpriseId" class="w-100" placeholder="请输入所属企业" filterable clearable @change="cloneAddress">
                      <el-option
                        v-for="(item,index) in enterpriseIds"
                        :key="index+'enterpriseId'"
                        :value="item.id"
                        :label="item.name"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="任务发布人" prop="publisherId">
                    <el-select v-model="dataForm.publisherId" class="w-100" placeholder="请输入任务发布人" filterable clearable :filter-method="dataFilter2">
                      <el-option
                        v-for="(item,index) in publisherIds"
                        :key="index+'publisherId'"
                        :value="item.id"
                        :label="item.realName"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="任务责任人" prop="responsibilityId">
                    <el-select v-model="dataForm.responsibilityId" class="w-100" placeholder="请输入任务责任人" filterable clearable :filter-method="dataFilter1">
                      <el-option
                        v-for="(item,index) in responsibilityIds"
                        :key="index+'responsibilityId'"
                        :value="item.id"
                        :label="item.realName"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="排放口形状" prop="form">
                    <el-input v-model="dataForm.form" placeholder="请输入排放口形状" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="初运行日期" prop="lnitialDate">
                    <el-date-picker v-model="dataForm.lnitialDate" placeholder="选择时间" style="width: 100%;" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="排放方式" prop="dischargeMode">
                    <el-select v-model="dataForm.dischargeMode" class="w-100" placeholder="请输入排放方式">
                      <el-option
                        v-for="(item,index) in dischargeModes"
                        :key="index+'dischargeMode'"
                        :value="item.code"
                        :label="item.codeName"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col v-show="dataForm.outletType==='e012_01'" :span="12">
                  <el-form-item label="自动停炉:">
                    <el-radio-group v-model="dataForm.stopProduction" class="search-radio-group">
                      <el-radio :label="1">打开</el-radio>
                      <el-radio :label="0">关闭</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="20">
                  <el-form-item label="经纬度：">
                    <el-input v-model="dataForm.outletLocation" />
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <el-button size="mini" @click="mapDialogVisible = true">点击地图</el-button>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="排口地址：">
                    <el-select v-model="dataForm.addressPId" filterable clearable @change="selectCity">
                      <el-option
                        v-for="(item, index) in provinceList"
                        :key="index+ '_province'"
                        :value="item.areaid"
                        :label="item.areaname"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item>
                    <el-select v-model="dataForm.cityId" filterable clearable @change="selectDistrict">
                      <el-option
                        v-for="(item, index) in cityList"
                        :key="index+ '_city'"
                        :value="item.areaid"
                        :label="item.areaname"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8" label="">
                  <el-form-item>
                    <el-select v-model="dataForm.address" filterable clearable>
                      <el-option
                        v-for="(item, index) in districtList"
                        :key="index+ '_district'"
                        :value="item.areaid"
                        :label="item.areaname"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="排口地址详细" prop="addressDetails">
                    <el-input v-model="dataForm.addressDetails" placeholder="请输入排口地址详细" @blur="blur" />
                  </el-form-item>
                </el-col>

                <el-col :span="22">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="dataForm.remark" placeholder="请输入备注" />
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="排放口图片" prop="outletPicture">
                    <UploadImage
                      :url="dataForm.outletPicture"
                      @setUrl="setUrl"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="数采仪信息" name="second">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="数采仪品牌" prop="dataInstrumentModel">
                    <el-input v-model="dataForm.dataInstrumentModel" placeholder="请输入数采仪品牌" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="仪器型号" prop="instrumentModel">
                    <el-input v-model="dataForm.instrumentModel" placeholder="请输入仪器型号" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="仪器编号" prop="instrumentConfiguration">
                    <el-input v-model="dataForm.instrumentConfiguration" placeholder="请输入仪器编号" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="拓展属性" name="third">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="回传间隔(秒)" prop="returnInterval">
                    <el-input v-model="dataForm.returnInterval" placeholder="请输入回传间隔(秒)" />
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="12">
                  <el-form-item label="恒值时间（小时）（废气、废水）" prop="constantTime">
                    <el-input-number v-model="dataForm.constantTime" placeholder="请输入恒值时间（小时）（废气、废水）" />
                  </el-form-item>
                </el-col> -->
                <el-col :span="12">
                  <el-form-item label="废气超标值时间(分钟)" prop="excessiveTime">
                    <el-input-number v-model="dataForm.excessiveTime" placeholder="请输入废气超标值时间(分钟)" />
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="12">
                  <el-form-item label="超标值次数（次）（废气、废水）" prop="excessiveTimes">
                    <el-input-number v-model="dataForm.excessiveTimes" placeholder="请输入超标值次数（次）（废气、废水）" />
                  </el-form-item>
                </el-col> -->
              </el-row>
            </el-tab-pane>
            <!-- <el-tab-pane label="废水属性" name="fourth">废水属性</el-tab-pane>
            <el-tab-pane label="废气属性" name="fifth">废气属性</el-tab-pane> -->
          </el-tabs>
        </template></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :loading="saveLoading" class="sure-btn" size="mini" type="primary" @click="handleSave">保存</el-button>
        <el-button size="mini" class="cancel-btn" @click="closeDialog">取消</el-button>
      </span>
      <el-dialog
        title="地图"
        :visible.sync="mapDialogVisible"
        width="40%"
        append-to-body
        @opened="addMarker"
        @close="removeOverlay"
      >
        <el-form class="dialog-form" label-width="100px">
          <el-row>
            <el-col :span="18">
              <el-form-item label="地理坐标：">
                <el-input v-model="coordinate" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <BaiduMap
          ref="map"
          @setPonit="setPonit"
        />
        <span slot="footer" class="dialog-footer">
          <el-button @click="mapDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="selectMap()">确定</el-button>
        </span>
      </el-dialog>
    </el-dialog>

  </div>
</template>

<script>
import { getDict } from '@/utils/dict'
import { add, edit } from '@/api/base/outlet'
// import { getList as getListEqu } from '@/api/info/equipmentType'
// import { getList as getListPro } from '@/api/info/projectDepartment'
import UploadImage from '@/components/UploadImage/index'
import { getEnterpriseByCd } from '@/api/system/common'
import { getProjectPersonnel } from '@/utils/common'
// import { getLocation } from '@/api/base/outlet'
import { getList as getDepartmentList } from '@/api/info/projectDepartment'
import BMap from 'BMap'
import BaiduMap from '@/components/BaiduMap/index'
import { getList, getInfo } from '@/api/system/area'

export default {
  name: 'AddDialog',
  components: { UploadImage, BaiduMap },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    dialogType: {
      type: String,
      default: 'detail'
    },
    obj: {
      type: Object,
      default: null
    },
    personnel: {
      type: Array,
      default: null
    }
  },
  data() {
    return {
      saveLoading: false,
      formLoading: false,
      dataForm: {
        id: null,
        outletName: null,
        outletMn: null,
        outletCode: null,
        outletType: null,
        enterpriseId: null,
        projectDepartmentId: null,
        publisherId: null,
        responsibilityId: null,
        form: null,
        lnitialDate: '',
        dischargeMode: null,
        position: null,
        remark: null,
        outletPicture: null,
        dataInstrumentModel: null,
        instrumentModel: null,
        instrumentConfiguration: null,
        returnInterval: null,
        constantTime: null,
        excessiveTime: null,
        excessiveTimes: null,
        outletLocation: null,
        addressDetails: null,
        address: null,
        stopProduction: 1
      },
      mapDialogVisible: false,
      coordinate: '',
      provinceList: [],
      cityList: [],
      districtList: [],
      outletTypes: [],
      enterpriseIds: [],
      projectDepartmentIds: [],
      dischargeModes: [],
      responsibilityIds: [],
      publisherIds: [],
      optionsCopy: [],
      instrumentModels: [{ id: 0, name: '普通数采仪-万维盈创' }],
      dialogImageUrl: '',
      activeName: 'first',
      rules: {
        outletName: [{ required: true, message: '请输入排放口名称', trigger: 'blur' }],
        outletMn: [{ required: true, message: '请输入MN', trigger: 'blur' }],
        outletType: [{ required: true, message: '请输入排放口类型', trigger: 'blur' }],
        enterpriseId: [{ required: true, message: '请选择所属企业', trigger: 'blur' }],
        projectDepartmentId: [{ required: true, message: '请选择所属部门', trigger: 'blur' }],
        publisherId: [{ required: true, message: '请选择任务发布人', trigger: 'blur' }],
        responsibilityId: [{ required: true, message: '请选择责任人', trigger: 'blur' }]

      }
    }
  },
  created() {
    this.outletTypes = getDict('e012')
    this.dischargeModes = getDict('e026')
    // 项目部
    getDepartmentList().then(res => {
      this.projectDepartmentIds = res.data.list
    })
    this.dischargeModes = getDict('e026')
    this.outletStatuss = getDict('e027')
  },
  methods: {
    initData() {
      this.formLoading = true
      this.saveLoading = false
      this.responsibilityIds = this.personnel
      this.publisherIds = this.personnel
      this.optionsCopy = this.personnel
      getEnterpriseByCd().then(res => {
        this.enterpriseIds = res.data.list
      })
      if (this.obj) {
        const obj = JSON.parse(JSON.stringify(this.obj))
        this.dataForm = obj
        this.coordinate = this.dataForm.outletLocation
        this.addressDetails = this.dataForm.addressDetails
      }
      this.getAreaList()
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      setTimeout(() => {
        this.formLoading = false
      }, 500)
    },
    selectEnterprise() {
      // this.dataForm.enterpriseId = null
      // 企业
      // getEnterpriseByCd({ 'projectDepartmentId': this.dataForm.projectDepartmentId }).then(res => {
      //   this.enterpriseIds = res.data.list
      // })
      this.dataForm.publisherId = null
      this.dataForm.responsibilityId = null
      getProjectPersonnel({ 'pid': this.dataForm.projectDepartmentId }).then(res => {
        this.responsibilityIds = res.data.row
        this.publisherIds = res.data.row
        this.optionsCopy = res.data.row
      })
    },
    cloneAddress() {
      this.enterpriseIds.forEach(v => {
        if (v.id === this.dataForm.enterpriseId) {
          this.dataForm.outletLocation = v.enterpriseLocation
          this.dataForm.addressDetails = v.enterpriseAddressDetails
          this.dataForm.addressPId = v.addressPId
          this.dataForm.cityId = v.enterpriseCityId
          this.dataForm.address = v.enterpriseAddressId
          this.getAreaList()
        }
      })
    },
    blur() {
      // 创建地址解析器实例
      var myGeo = new BMap.Geocoder()
      // 将地址解析结果显示在地图上，并调整地图视野
      myGeo.getPoint(this.dataForm.addressDetails, point => {
        if (point) {
          var po = point.lng + ',' + point.lat
          this.dataForm.outletLocation = po
        } else {
          alert('您选择的地址没有解析到结果！')
        }
      }, '四川省')
    },
    handleSave() {
      if (this.dataForm.outletType !== 'e012_01') {
        this.dataForm.stopProduction = null
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.saveLoading = true
          if (this.dataForm.id) {
            edit(this.dataForm).then(() => {
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.$emit('flushPage')
              this.$emit('closeDialog')
              this.clearData()
              this.saveLoading = false
            }).catch(() => {
              this.saveLoading = false
            })
          } else {
            add(this.dataForm).then(() => {
              this.$message.success('添加成功')
              this.$emit('flushPage')
              this.$emit('closeDialog')
              this.clearData()
              this.saveLoading = false
            }).catch(() => {
              this.saveLoading = false
            })
          }
        }
      })
    },
    closeDialog() {
      this.$emit('closeDialog')
      this.clearData()
      this.$refs['form'].clearValidate()
    },
    clearData() {
      this.dataForm = {
        id: null,
        outletName: null,
        outletMn: null,
        outletCode: null,
        outletType: null,
        enterpriseId: null,
        projectDepartmentId: null,
        publisherId: null,
        responsibilityId: null,
        form: null,
        lnitialDate: '',
        dischargeMode: null,
        position: null,
        remark: null,
        outletPicture: null,
        dataInstrumentModel: null,
        instrumentModel: null,
        instrumentConfiguration: null,
        returnInterval: null,
        constantTime: null,
        excessiveTime: null,
        excessiveTimes: null,
        outletLocation: null,
        addressDetails: null,
        address: null,
        stopProduction: 1
      }
      this.activeName = 'first'
      this.coordinate = ''
      this.addressDetails = ''
    },
    setUrl(url) {
      this.dataForm.outletPicture = url
    },
    handleClick(tab, event) {
    },
    dataFilter1(val) {
      this.dataForm.responsibilityId = val // 吞掉了第一次输入,赋值回给输入框
      if (val) { // val存在
        this.responsibilityIds = this.optionsCopy.filter((item) => {
          if (!!~item.username.indexOf(val) || !!~item.username.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          } else if (!!~item.realName.indexOf(val) || !!~item.realName.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          } else if (!!~item.namePym.indexOf(val) || !!~item.namePym.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          }
        })
      } else { // val为空时，还原数组
        this.responsibilityIds = this.optionsCopy
      }
    },
    dataFilter2(val) {
      this.dataForm.publisherId = val // 吞掉了第一次输入,赋值回给输入框
      if (val) { // val存在
        this.publisherIds = this.optionsCopy.filter((item) => {
          if (!!~item.username.indexOf(val) || !!~item.username.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          } else if (!!~item.realName.indexOf(val) || !!~item.realName.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          } else if (!!~item.namePym.indexOf(val) || !!~item.namePym.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          }
        })
      } else { // val为空时，还原数组
        this.publisherIds = this.optionsCopy
      }
    },
    selectMap() {
      this.dataForm.outletLocation = this.coordinate
      this.dataForm.addressDetails = this.addressDetails
      this.mapDialogVisible = false
    },
    setPonit(data) {
      this.coordinate = data.point.lng + ',' + data.point.lat
      const geoc = new BMap.Geocoder()
      const ponit = new BMap.Point(data.point.lng, data.point.lat)
      geoc.getLocation(ponit, (res) => {
        this.addressDetails = res.address
      })
    },
    addMarker() {
      if (this.dataForm.outletLocation === '' || this.dataForm.outletLocation === null) {
        return
      }
      const gps = this.dataForm.outletLocation.split(',')
      this.$refs.map.addMarker(gps[0], gps[1])
    },
    removeOverlay() {
      this.$refs.map.removeOverlay()
    },
    getAreaList() {
      if (this.dataForm.address !== null) {
        getInfo(this.dataForm.address).then(res => {
          const addressObj = res.data.obj
          if (addressObj) {
            this.dataForm.cityId = addressObj.parentid
            // this.selectDistrict(addressObj.parentid)
            getList({ parentid: addressObj.parentid }).then(res => {
              this.districtList = res.data.list
            })
            getInfo(addressObj.parentid).then(res => {
              this.dataForm.addressPId = res.data.obj.parentid
              //  this.selectCity(res.data.obj.parentid)
              getList({ parentid: res.data.obj.parentid }).then(res => {
                this.cityList = res.data.list
              })
            })
          }
        })
      }
      getList({ parentid: 0 }).then(res => {
        this.provinceList = res.data.list
      })
    },
    selectCity(val) {
      getList({ parentid: val }).then(res => {
        this.cityList = res.data.list
        this.dataForm.cityId = ''
        this.dataForm.address = ''
      })
    },
    selectDistrict(val) {
      getList({ parentid: val }).then(res => {
        this.districtList = res.data.list
        this.dataForm.address = ''
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
